package com.zhuhjay.service.system.wxmp.config;

import com.zhuhjay.service.system.wxmp.handler.*;
import com.zhuhjay.service.system.wxmp.interceptor.MessageLimiterInterceptor;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.EventType.UNSUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;

/**
 * @author ZhuHJay
 * @date 2023/8/2 22:17
 */
@Configuration
@AllArgsConstructor
public class WxMpMessageConfig {

    private final LogHandler logHandler;
    private final LocationHandler locationHandler;
    private final MessageHandler messageHandler;
    private final UnsubscribeHandler unsubscribeHandler;
    private final SubscribeHandler subscribeHandler;
    private final MessageLimiterInterceptor messageLimiterInterceptor;

    @Bean
    public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
        final WxMpMessageRouter router = new WxMpMessageRouter(wxMpService);
        // 记录所有事件的日志 （异步执行）
        router.rule().handler(logHandler).next();
        // 关注事件
        router.rule().async(false).msgType(EVENT).event(SUBSCRIBE)
                .handler(subscribeHandler).end();
        // 取消关注事件
        router.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE)
                .handler(unsubscribeHandler).end();
        // 上报地理位置事件
        router.rule().async(false).msgType(EVENT).event(WxConsts.EventType.LOCATION)
                .handler(locationHandler).end();
        // 接收地理位置消息
        router.rule().async(false).msgType(WxConsts.XmlMsgType.LOCATION)
                .handler(locationHandler).end();
        // 默认
        router.rule().async(false)
                .interceptor(messageLimiterInterceptor)
                .handler(messageHandler).end();
        return router;
    }

}
